package io.xxx.omni.osc.sdk

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.dateTimeFormatPattern
import io.xxx.omni.osc.common.dateTimeFormatter
import io.xxx.omni.osc.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.time.OffsetDateTime
import java.util.*

@Component
class JdClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "http://114.67.174.95/routerjson"

    fun execute(store: Store, method: String, request: Map<String, Any>): JSONObject {
        val authorization = store.authorization
        val signMap = TreeMap<String, String>()
        signMap["method"] = method
        signMap["access_token"] = authorization["access_token"]
        signMap["app_key"] = authorization["app_key"]
        signMap["timestamp"] = OffsetDateTime.now().format(dateTimeFormatter)
        signMap["360buy_param_json"] = JSON.toJSONStringWithDateFormat(request, dateTimeFormatPattern)
        signMap["v"] = "2.0"
        val builder = StringBuilder()
            .append(authorization["app_secret"])
            .append(signMap.entries.joinToString("") { it.key + it.value })
            .append(authorization["app_secret"])
        val sign = DigestUtils.md5Hex(builder.toString()).uppercase()

        val urlBuilder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
        signMap.forEach { urlBuilder.queryParam(it.key, it.value) }
        urlBuilder.queryParam("sign", sign)
        val url = urlBuilder.build(false).toUriString()
        return restTemplate.getForEntity(url, JSONObject::class.java).body!!
    }
}